package com.ymx.darling.generater;

import com.ymx.darling.exception.DarlingException;
import com.ymx.darling.generater.config.GlobalConfig;
import com.ymx.darling.generater.config.StrategyConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 基础生成器
 * @author 爱Java的小于
 */
public class BaseGenerator {
    protected final GlobalConfig globalConfig;
    protected final StrategyConfig strategyConfig;

    public BaseGenerator(GlobalConfig globalConfig, StrategyConfig strategyConfig) {
        this.globalConfig = globalConfig;
        this.strategyConfig = strategyConfig;
    }

    /**
     * 构建Class文件
     * @param  className className
     * @param classContext classContext
     */
    public void createClass(String className, String classContext) {
        String dirPath = this.getDirPath(className);
        File file = new File(dirPath);
        if (!file.exists()) {
            if (!file.mkdir()) {
                throw new DarlingException("文件夹"+dirPath+"创建失败");
            }
        }
        try (FileWriter writer = new FileWriter(className)) {
            writer.write(classContext);
            writer.flush();
            System.out.println(className);
        } catch (IOException e) {
            throw new DarlingException("文件写入失败,错误详情:"+e.getMessage());
        }
    }

    private String getDirPath(String filePath) {
        String[] split = filePath.split("\\\\");
        StringBuilder pathBuilder = new StringBuilder();
        for (int i = 0; i < split.length - 1; i++) {
            pathBuilder.append(split[i]).append("\\");
        }

        return pathBuilder.toString();
    }


    public String getProjectAbsolutePath() {
        return System.getProperty("user.dir") + "\\" + globalConfig.getProjectRoot();
    }


    /**
     * 下划线转驼峰式
     * @param input input
     * @return String
     */
    public String convertToCamelCase(String input) {
        StringBuilder camelCaseStr = new StringBuilder();
        boolean nextUpperCase = false;

        for (char character : input.toCharArray()) {
            if (character == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    camelCaseStr.append(Character.toUpperCase(character));
                    nextUpperCase = false;
                } else {
                    camelCaseStr.append(character);
                }
            }
        }

        return camelCaseStr.toString();
    }

    /**
     * 首字母转大写
     * @param s s
     * @return s
     */
    public String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }
}
